import { parse } from 'utils/';
import * as QRious from 'qrious';

/**
 * 商品模块
 * @type {Object}
 */
export default [
  {
    name: '文件上传',
    method: 'upload',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.file(data).subscribe(fn, errFn);
    }
  }, {
    name: '书籍查询',
    method: 'book',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('books', query => {
        if (data.id) {
          query.equalTo('objectId', data.id);
        } else {
          query.contains('name', data);
        }
        query.limit(20);
      })
        .filter(x => x.type && x.type === 'result')
        .map(x => x.result)
        .subscribe(next => fn(next));
    }
  }, {
    name: '章节查询',
    method: 'chapter',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('chapters', query => {
        if (data.id) {
          query.equalTo('objectId', data.id);
        } else {
          query.contains('title', data);
        }
        query.limit(20)
      })
        .filter(x => x.type && x.type === 'result')
        .map(x => x.result)
        .subscribe(next => fn(next));
    }
  }, {
    name: '问题查询',
    method: 'question',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      parse.query('question_banks', query => {
        if (data.id) {
          query.equalTo('objectId', data.id);
        } else {
          query.contains('question', data);
        }
        query.limit(20)
      })
        .filter(x => x.type && x.type === 'result')
        .map(x => x.result)
        .subscribe(next => fn(next));
    }
  }, {
    name: '二维码生成',
    method: 'qrcode',
    type: 'parse',
    excute: ({ data, fn, errFn } = {}) => {
      // 处理中文问题
      const utf16to8 = str => {
        const len = str.length;
        let out = '';

        for (let i = 0; i < len; i++) {
          const c = str.charCodeAt(i);
          if ((c >= 0x0001) && (c <= 0x007F)) {
            out += str.charAt(i);
          } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
          } else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
          }
        }
        return out;
      }
      const qrcode = new QRious({
        background: 'white',
        backgroundAlpha: 1.0,
        foreground: 'black',
        foregroundAlpha: 1.0,
        level: 'L',
        mime: 'image/png',
        padding: null,
        size: 200,
        value: utf16to8(data)
      });
      fn(qrcode.image);
    }
  }
];